package com.adminx.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.adminx.dao.AuthorityDao;
import com.adminx.dao.AuthorityResourceDao;
import com.adminx.entity.Authority;
import com.adminx.pojo.AuthorityPojo;
import com.adminx.util.PageResults;

@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class AuthorityService {
	
	
	@Autowired
	private AuthorityDao authorityDao;
	
	@Autowired
	private AuthorityResourceDao authorityResourceDao;
	
	/**
	 * 分页查询权限
	 * @param map
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 */
	public PageResults<AuthorityPojo> query(Integer pageIndex, Integer pageSize, String searchText){
		return this.authorityDao.query(pageIndex, pageSize, searchText);
	}
	
	/**
	 * 查询�?��权限
	 * @param map
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 */
	public List<AuthorityPojo> findAuthorityList(Long roleID){
		return this.authorityDao.findAuthorityList(roleID);
	}
	
	/**
	 * 通过ID查询权限
	 * @param authorityId
	 * @return Authority
	 */
	public Authority info(Long authorityId) {
		String hql = "From Authority t where t.authorityId = ?";
		return this.authorityDao.getByHQL(hql,authorityId);
	}
	
	/**
	 * 通过ID删除权限
	 * @param accountId
	 */
	public int delBatch(String ids){
		return this.authorityDao.delBatch(ids);
	}
	
	/**
	 * 保存或修改权�?
	 * @param authority
	 */
	public void save(Authority authority) {
		//新增
		if(authority.getAuthorityId() == null){
			this.authorityDao.save(authority);
		}
		//修改
		else{
			Authority oldAuthority = this.authorityDao.get(authority.getAuthorityId());
			oldAuthority.setAuthorityName(authority.getAuthorityName());
			oldAuthority.setRemark(authority.getRemark());
			oldAuthority.setUpdateDate(new Date());
			oldAuthority.setCreateDate(authority.getCreateDate());
			this.authorityDao.update(oldAuthority);
		}
	}
	
	/**
	 * 保存资源权限
	 */
	public void saveResourceByAuthorityId(String multiSelectedValue, Long authorityId){
		//删除权限原有资源
		this.authorityResourceDao.delResourceByAuthority(authorityId);
		//保存权限资源
		this.authorityResourceDao.saveResourceByAuthorityId(multiSelectedValue, authorityId);
	}
	
	/**
	 * 通过权限查询�?��资源
	 * @return
	 */
	public StringBuilder getResourceByAuthority(Long authorityId){
		return this.authorityDao.getResourceByAuthority(authorityId);
	}
}
